package com.jtjrenren.android.taxi.passenger.manger.api;

import com.jtjrenren.android.taxi.passenger.Constants;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiBestCoupn;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiRechargList;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiConfig;
import com.jtjrenren.android.taxi.passenger.manger.AppManger;
import com.jtjrenren.android.taxi.passenger.R;
import com.jtjrenren.android.taxi.passenger.bean.ApiCarListArea;
import com.jtjrenren.android.taxi.passenger.bean.User;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiAmount;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiCommonResult;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiCouList;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiDriver;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiHistoryItem;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiJdList;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiMaList;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiOrderDetails;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiResultCommonStr;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiUpVersion;
import com.jtjrenren.android.taxi.passenger.bean.api.Complaint;
import com.jtjrenren.android.taxi.passenger.bean.api.ComplaintList;
import com.jtjrenren.android.taxi.passenger.bean.api.CurrentOrderCost;
import com.jtjrenren.android.taxi.passenger.bean.api.DriverEvaResult;
import com.jtjrenren.android.taxi.passenger.bean.api.DriverImgs;
import com.jtjrenren.android.taxi.passenger.bean.api.DriverToCustomer;
import com.jtjrenren.android.taxi.passenger.bean.api.ESpecarCost;
import com.jtjrenren.android.taxi.passenger.bean.api.Result;
import com.jtjrenren.android.taxi.passenger.utils.ExceptionHand;
import com.library.utils.GsonUtils;
import com.library.utils.LogUtil;
import com.library.utils.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/9/6.
 */

public class ApiWorks {
    private static final String SERVER_URL = AppManger.getInstance().getString(R.string.url_base);
    private static final String UNICODE = AppManger.getInstance().getString(R.string.unicode);
    private static final String COMPANYID = "";

    private static ApiService apiService = creatClient().create(ApiService.class);

    public static void checkAppConfig(final ResponseListener<ApiConfig> listener) {
        apiService.checkAppConfig(getCommonParams("Public", "GetAppConfig")).map(new Func1<String, ApiConfig>() {
            @Override
            public ApiConfig call(String s) {
                if (!StringUtils.isEmpty(s)) {
                    LogUtil.log("config", "AppConfig:" + s);
                    return GsonUtils.getObj(s, ApiConfig.class);
                }
                return null;
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiConfig>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiConfig config) {
                listener.onResponse(config);
            }
        });
    }

    public static void checkNewVersion_M(String version, final ResponseListener<ApiUpVersion.VersionEntity> listener) {
        apiService.checkNewVersion_M(getCommonParams("Public", "CheckVersion"), version, "0", "1").map(new Func1<String, ApiUpVersion.VersionEntity>() {
            @Override
            public ApiUpVersion.VersionEntity call(String jsonStr) {
                ApiUpVersion.VersionEntity versionEntity = null;
                if (!StringUtils.isEmpty(jsonStr)) {
                    ApiUpVersion version = GsonUtils.getObj(jsonStr, ApiUpVersion.class);
                    if (version.getCode() == 1 && version.getData().size() > 0)
                        versionEntity = version.getData().get(0);
                }
                return versionEntity;
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiUpVersion.VersionEntity>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);

            }

            @Override
            public void onNext(ApiUpVersion.VersionEntity versionEntity) {
                listener.onResponse(versionEntity);
            }
        });
    }

    public static void checkPhoneUnie(String phone, final ResponseListener<ApiResultCommonStr> listener) {
        apiService.checkPhoneUnie(getCommonParams("Public", "IsUniquePhone"), phone, "0")

                .map(new Func1<String, ApiResultCommonStr>() {
                    @Override
                    public ApiResultCommonStr call(String result) {
                        ApiResultCommonStr r = new ApiResultCommonStr(0, "手机号已被注册", null);

                        if (!StringUtils.isEmpty(result)) {
                            Result obj = GsonUtils.getObj(result, Result.class);
                            if (obj != null && "US0017".equals(obj.getResult()))
                                r.setCode(1);
                        }
                        return r;
                    }
                })
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ApiResultCommonStr>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (listener != null) listener.onResponse(null);
                        ExceptionHand.handException(e);
                    }

                    @Override
                    public void onNext(ApiResultCommonStr s) {
                        if (listener != null)
                            listener.onResponse(s);
                    }
                });
    }

    public static void checkUserCall(String userID, final ResponseListener<ApiCommonResult> listener) {
        apiService.checkUserCall(getCommonParams("Order", "P_TaxiCall_CheckCall"), userID)

                .map(new Func1<String, ApiCommonResult>() {
                    @Override
                    public ApiCommonResult call(String jsonStr) {
                        return GsonUtils.getObj(jsonStr, ApiCommonResult.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiCommonResult>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiCommonResult s) {
                if (listener != null)
                    listener.onResponse(s);
            }
        });
    }


    public static void login(String phone, String pwd, final ResponseListener<ApiResultCommonStr> listener) {
        apiService.login(getCommonParams("User", "UserLoginCheck"), phone, pwd, COMPANYID)

                .map(new Func1<String, ApiResultCommonStr>() {
                    @Override
                    public ApiResultCommonStr call(String jsonStr) {
                        ApiResultCommonStr result = new ApiResultCommonStr(0, "登录失败", null);
                        if (!StringUtils.isEmpty(jsonStr)) {
                            result.setCode(1);
                            result.setData(jsonStr);
                        }
                        return result;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ApiResultCommonStr>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (listener != null) listener.onResponse(null);
                        ExceptionHand.handException(e);
                    }

                    @Override
                    public void onNext(ApiResultCommonStr s) {
                        if (listener != null) listener.onResponse(s);
                    }
                });
    }

    public static void sendAuthCode(String phone, String type, final ResponseListener<String> listener) {
        LogUtil.log("applog", "发送验证码：");
        apiService.sendAuthCode(getCommonParams("Public", "SendAuthCode"), phone, type)
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        LogUtil.log("applog", "获取验证码结果：" + s);
                        return s;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (listener != null) listener.onResponse(null);
                        LogUtil.log("applog", "发送验证码：" + e.toString());
                        ExceptionHand.handException(e);
                    }

                    @Override
                    public void onNext(String s) {
                        if (listener != null)
                            listener.onResponse(s);
                    }
                });
    }

    public static void loginByAuthCode(String phone, String code, String type, final ResponseListener<ApiResultCommonStr> listener) {
        apiService.loginByAuthCode(getCommonParams("User", "AuthenticatePhoneRegister"), phone, code, type, COMPANYID)
                .map(new Func1<String, ApiResultCommonStr>() {
                    @Override
                    public ApiResultCommonStr call(String jsonStr) {
                        ApiResultCommonStr result = new ApiResultCommonStr(0, "登录失败", null);
                        if (!StringUtils.isEmpty(jsonStr)) {
                            result.setCode(1);
                            result.setData(jsonStr);
                        }
                        return result;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiResultCommonStr>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiResultCommonStr s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }


    public static void authPhoneByCode(String key, String phone, String type, final ResponseListener<ApiResultCommonStr> listener) {
        LogUtil.log("yzm", "验证：" + phone + "-->" + key);
        apiService.authPhoneByCode(getCommonParams("Public", "AuthenticatePhoneByCode"), key, phone, type)
                .map(new Func1<String, ApiResultCommonStr>() {
                    @Override
                    public ApiResultCommonStr call(String s) {
                        LogUtil.log("yzm", "验证结果：" + s);
                        ApiResultCommonStr resultCommonStr = new ApiResultCommonStr(0, "", "");
                        if (!StringUtils.isEmpty(s)) {
                            try {
                                JSONObject object = new JSONObject(s);
                                if (object.has("Result") && "SM0009".equals(object.getString("Result")))
                                    resultCommonStr.setCode(1);
                            } catch (JSONException e) {
                            }
                        }
                        return resultCommonStr;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiResultCommonStr>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiResultCommonStr s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }


    public static void registerByPhone(String phone, String pwd, final ResponseListener<String> listener) {
        LogUtil.log("register", "开始注册:" + phone + "," + pwd);
        apiService.registerByPhone(getCommonParams("User", "PhonePwdRegister"), phone, pwd, COMPANYID)
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        return s;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null)
                    listener.onResponse(null);
                LogUtil.log("register", "注册异常:" + e.toString());
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(String s) {
                LogUtil.log("register", "注册回调:" + s);
                if (listener != null)
                    listener.onResponse(s);
            }
        });
    }

    public static void ResetPassword(String phone, String pwd, final ResponseListener<ApiResultCommonStr> listener) {
        apiService.ResetPassword(getCommonParams("User", "ResetPassword"), phone, pwd, COMPANYID).map(new Func1<String, ApiResultCommonStr>() {
            @Override
            public ApiResultCommonStr call(String s) {
                ApiResultCommonStr resultCommonStr = new ApiResultCommonStr(0, "", "");
                if (!StringUtils.isEmpty(s)) {
                    Result obj = GsonUtils.getObj(s, Result.class);
                    if (obj != null && "US0010".equals(obj.getResult()))
                        resultCommonStr.setCode(1);
                }
                return resultCommonStr;
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiResultCommonStr>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiResultCommonStr s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getUserDetails(String userId, final ResponseListener<User> listener) {
        apiService.getUserDetails(getCommonParams("User", "GetClientDetail"), userId, COMPANYID)
                .map(new Func1<String, User>() {
                    @Override
                    public User call(String s) {
                        User details = null;
                        if (!StringUtils.isEmpty(s))
                            details = GsonUtils.getObj(s, User.class);
                        return details;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<User>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(User s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void updateUserInfo(User user, final ResponseListener<Result> listener) {
        apiService.updateUserInfo(getCommonParams("User", "UpdateUserInfo"), user.getWorkNo(), user.getName() == null ? "" : user.getName(),
                user.getSex() == null ? "1" : user.getSex(), user.getAge() == null ? "" : user.getAge(), user.getPostAddress() == null ? "" : user.getPostAddress()
        ).map(new Func1<String, Result>() {
            @Override
            public Result call(String s) {
                Result result = null;
                if (!StringUtils.isEmpty(s))
                    result = GsonUtils.getObj(s, Result.class);
                return result;
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Result>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(Result s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getUserAmountDetails(String userId, final ResponseListener<ApiAmount> listener) {
        LogUtil.log("wallect", "账号信息：请求获取！---API");
        apiService.getUserAmountDetails(getCommonParams("User", "GetUserCashInfo"), userId)
                .map(new Func1<String, ApiAmount>() {
                    @Override
                    public ApiAmount call(String s) {
                        LogUtil.log("wallect", "账号信息：" + s);
                        ApiAmount result = null;
                        if (!StringUtils.isEmpty(s))
                            result = GsonUtils.getObj(s, ApiAmount.class);
                        return result;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiAmount>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                LogUtil.log("wallect", "账号信息：" + e.toString());
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiAmount s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getChargeHistory(String userId, final ResponseListener<ApiRechargList> listener) {
        apiService.getChargeHistory(getCommonParams("Pocket", "Custormer_RechargeLists"), userId)
                .map(new Func1<String, ApiRechargList>() {
                    @Override
                    public ApiRechargList call(String s) {
                        ApiRechargList rechargList = null;
                        if (!StringUtils.isEmpty(s))
                            rechargList = GsonUtils.getObj(s, ApiRechargList.class);
                        return rechargList;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiRechargList>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiRechargList s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }


    public static void getDriverDetails(String driverId, final ResponseListener<ApiDriver> listener) {

        apiService.getDriverDetails(getCommonParams("Driver", "GetDriverDetailToCustomer"), driverId, COMPANYID)
                .map(new Func1<String, ApiDriver>() {
                    @Override
                    public ApiDriver call(String s) {
                        ApiDriver apiDriver = null;
                        if (!StringUtils.isEmpty(s))
                            apiDriver = GsonUtils.getObj(s, ApiDriver.class);
                        return apiDriver;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiDriver>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiDriver s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getDriverEvaluationList(String driverCounts, String driverId, int pageIndex, int pageSize, final ResponseListener<DriverEvaResult> listener) {
        apiService.getDriverEvaluationList(getCommonParams("Evaluation", "GetEvalustionList"), StringUtils.isEmpty(driverCounts) ? "" : driverCounts, driverId, pageIndex, pageSize)
                .map(new Func1<String, DriverEvaResult>() {
                    @Override
                    public DriverEvaResult call(String jsonResult) {
                        DriverEvaResult driverEvaResult = null;
                        if (!StringUtils.isEmpty(jsonResult))
                            driverEvaResult = GsonUtils.getObj(jsonResult, DriverEvaResult.class);
                        return driverEvaResult;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<DriverEvaResult>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(DriverEvaResult s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getDriverImgs(String carNO, int pageIndex, int pageSize, final ResponseListener<DriverImgs> listener) {
        apiService.getDriverImgs(getCommonParams("Evaluation", "GetCarPhotoes"), carNO, pageIndex, pageSize)
                .map(new Func1<String, DriverImgs>() {
                    @Override
                    public DriverImgs call(String jsonResult) {
                        DriverImgs driverImgs = null;
                        if (!StringUtils.isEmpty(jsonResult))
                            driverImgs = GsonUtils.getObj(jsonResult, DriverImgs.class);

                        return driverImgs;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<DriverImgs>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(DriverImgs s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }


    public static void evaluationAdd(String orderID, String userID, String driverID, int level, String contents, final ResponseListener<ApiResultCommonStr> listener) {
        LogUtil.log("order", "评价：" + level + "--" + contents);
        apiService.evaluationAdd(getCommonParams("Evaluation", "EvaluationAdd_New"), orderID, userID, driverID, level, contents)

                .map(new Func1<String, ApiResultCommonStr>() {
                    @Override
                    public ApiResultCommonStr call(String s) {
                        ApiResultCommonStr resultCommonStr = new ApiResultCommonStr(0, "", "");
                        if (!StringUtils.isEmpty(s)) {
                            Result result = GsonUtils.getObj(s, Result.class);
                            if (result != null && "EL0001".equals(result.getResult())) {
                                resultCommonStr.setCode(1);
                            } else if (result != null && "EL0002".equals(result.getResult())) {
                                resultCommonStr.setCode(2);
                            }
                        }
                        return resultCommonStr;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiResultCommonStr>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiResultCommonStr s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }


    public static void updateJinDou(String userID, int credit, String touType, final ResponseListener<String> listener) {
        apiService.updateJinDou(getCommonParams("KongtouStore", "UpdateCredits"), userID, credit, touType)

                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        return null;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(String s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getMaterialList(final ResponseListener<ApiMaList> listener) {
        apiService.getMaterialList(getCommonParams("KongtouStore", "MaterialList"))
                .map(new Func1<String, ApiMaList>() {
                    @Override
                    public ApiMaList call(String s) {
                        return GsonUtils.getObj(s, ApiMaList.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiMaList>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiMaList s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getJinDouHistory(String userId, final ResponseListener<ApiJdList> listener) {
        apiService.getJinDouHistory(getCommonParams("KongtouStore", "RecordList"), userId)

                .map(new Func1<String, ApiJdList>() {
                    @Override
                    public ApiJdList call(String s) {
                        return GsonUtils.getObj(s, ApiJdList.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiJdList>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiJdList s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getCompainList(final ResponseListener<Complaint> listener) {
        apiService.getCompainList(getCommonParams("Complaint", "ReturnCompainList"))

                .map(new Func1<String, Complaint>() {
                    @Override
                    public Complaint call(String s) {
                        return GsonUtils.getObj(s, Complaint.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Complaint>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(Complaint s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getCompaintByOrderID(String orderId, final ResponseListener<ComplaintList> listener) {
        apiService.getCompaintByOrderID(getCommonParams("Complaint", "GetComplaint"), orderId)

                .map(new Func1<String, ComplaintList>() {
                    @Override
                    public ComplaintList call(String s) {
                        return GsonUtils.getObj(s, ComplaintList.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ComplaintList>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ComplaintList s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }


    public static void addCompaint(String orderID, String userID, String driversID, String content, String complainCode, final ResponseListener<ApiResultCommonStr> listener) {
        apiService.addCompaint(getCommonParams("Complaint", "ComplaintionAdd"), orderID, userID, driversID
                , content, complainCode)
                .map(new Func1<String, ApiResultCommonStr>() {
                    @Override
                    public ApiResultCommonStr call(String s) {
                        ApiResultCommonStr apiResultCommonStr = new ApiResultCommonStr(0, "", "");
                        Result result = GsonUtils.getObj(s, Result.class);
                        if (result != null && result.getResult().equals("CP0001"))
                            apiResultCommonStr.setCode(1);

                        return apiResultCommonStr;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiResultCommonStr>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiResultCommonStr s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }


    public static void replayCompaint(String complaintID, String contentOfReply, final ResponseListener<String> listener) {
        apiService.replayCompaint(getCommonParams("Complaint", "ComplaintionReply"), complaintID, contentOfReply)
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        return null;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(String s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }


    public static void getAreaCarList(String lat, String lon, int cartype, final ResponseListener<ApiCarListArea> listener) {
        apiService.getAreaCarList(getCommonParams("Z_MapGPS", "AreaRadiusCar_Z"), lat, lon, cartype, Constants.CONFIG_SEARCHE_AREA_RADIUS, "1", COMPANYID)
                .map(new Func1<String, ApiCarListArea>() {
                    @Override
                    public ApiCarListArea call(String s) {
                        return GsonUtils.getObj(s, ApiCarListArea.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiCarListArea>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiCarListArea s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getOrderDetailByOrderSerNo(String orderSerno, final ResponseListener<ApiOrderDetails> listener) {
        apiService.getOrderDetailByOrderSerNo(getCommonParams("Order", "GetSignalOrderDetail_All"), orderSerno)

                .map(new Func1<String, ApiOrderDetails>() {
                    @Override
                    public ApiOrderDetails call(String s) {
                        return GsonUtils.getObj(s, ApiOrderDetails.class);
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ApiOrderDetails>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (listener != null) listener.onResponse(null);
                        ExceptionHand.handException(e);
                    }

                    @Override
                    public void onNext(ApiOrderDetails s) {
                        if (listener != null) listener.onResponse(s);
                    }
                });
    }

    public static void getOrderCurrCost(String orderId, final ResponseListener<CurrentOrderCost> listener) {
        apiService.getOrderCurrCost(getCommonParams("Z_Cost", "GetCurrentdata"), orderId)

                .map(new Func1<String, CurrentOrderCost>() {
                    @Override
                    public CurrentOrderCost call(String s) {
                        LogUtil.log("order", "当前返回的订单信息：" + s);
                        return GsonUtils.getObj(s, CurrentOrderCost.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<CurrentOrderCost>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(CurrentOrderCost s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void estimateSpecarCost(String startAddr, String startLat, String startLng, String endAddr, String endLat, String endLng, String carType, String useTime, String userID, final ResponseListener<ESpecarCost> listener) {
        apiService.estimateSpecarCost(getCommonParams("Z_Cost", "Z_EstimatedCost"), startAddr, startLat, startLng, endAddr, endLat, endLng, carType, useTime, userID)
                .map(new Func1<String, ESpecarCost>() {
                    @Override
                    public ESpecarCost call(String s) {
                        LogUtil.log("ecost","预估费用结果："+s);
                        return GsonUtils.getObj(s, ESpecarCost.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ESpecarCost>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ESpecarCost s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getOrderHistory_M(String userId, int pageSize, int curPage, int type, final ResponseListener<ApiHistoryItem> listener) {
        apiService.getOrderHistory_M(getCommonParams("Order", "GetHistoryOrder_M"), userId, pageSize, curPage, type)
                .map(new Func1<String, ApiHistoryItem>() {
                    @Override
                    public ApiHistoryItem call(String s) {
                        LogUtil.log("order", "历史订单:" + s);
                        return GsonUtils.getObj(s, ApiHistoryItem.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiHistoryItem>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiHistoryItem s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getDriverPostion(String driversID,
                                        String carNo, String terminal, String customerLat,
                                        String customerLng, final ResponseListener<DriverToCustomer> listener) {
        apiService.getDriverPostion(getCommonParams("Order", "GetDistanceCartoCustomer"), driversID, carNo, terminal, customerLat, customerLng)
                .map(new Func1<String, DriverToCustomer>() {
                    @Override
                    public DriverToCustomer call(String s) {
                        return GsonUtils.getObj(s, DriverToCustomer.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<DriverToCustomer>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(DriverToCustomer s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getCouponList(String userId, int type, final ResponseListener<ApiCouList> listener) {
        apiService.getCouponList(getCommonParams("User", "ReturnCouponsUsingList_CarType"), userId, type)
                .map(new Func1<String, ApiCouList>() {
                    @Override
                    public ApiCouList call(String s) {
                        return GsonUtils.getObj(s, ApiCouList.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiCouList>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiCouList s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getCouponBest(String userId, String lat,
                                     String lon, String money, String type, final ResponseListener<ApiBestCoupn> listener) {
        apiService.getCouponBest(getCommonParams("User", "ReturnOneUsingCoupons_CarType"), userId, lat,
                lon, money, type)
                .map(new Func1<String, ApiBestCoupn>() {
                    @Override
                    public ApiBestCoupn call(String s) {
                        return GsonUtils.getObj(s, ApiBestCoupn.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiBestCoupn>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiBestCoupn s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }


    public static void getChargeSerNo(String userId, String tradeFair,
                                      String tradeType, final ResponseListener<Result> listener) {
        apiService.getChargeSerNo(getCommonParams("Pocket", "CreateRechargeOrder_Type"), "App", userId, tradeFair,
                tradeType).map(new Func1<String, Result>() {
            @Override
            public Result call(String s) {
                return GsonUtils.getObj(s, Result.class);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Result>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                LogUtil.log("pay", "获取充值流水号出现异常！" + e.toString());
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(Result s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getPaySerNo_M(String orderID, String money, String payMode, String couponsID, String couponsAmt,
                                     final ResponseListener<ApiCommonResult> listener) {
        apiService.getPaySerNo_M(getCommonParams("Pocket", "CreatePayOrder_Type_M"), orderID, money, payMode, couponsID, couponsAmt)

                .map(new Func1<String, ApiCommonResult>() {
                    @Override
                    public ApiCommonResult call(String s) {
                        return GsonUtils.getObj(s, ApiCommonResult.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiCommonResult>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(ApiCommonResult s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void doQbPay_M(String orderID, String moneydes, String couponsID, String couponsAmt, final ResponseListener<ApiCommonResult> listener) {
        apiService.doQbPay_M(getCommonParams("Pocket", "PayRecord_M"), orderID,
                moneydes, couponsAmt, couponsID, "0", "0").map(new Func1<String, ApiCommonResult>() {
            @Override
            public ApiCommonResult call(String s) {
                return GsonUtils.getObj(s, ApiCommonResult.class);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ApiCommonResult>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);

            }

            @Override
            public void onNext(ApiCommonResult s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }


    public static void createCouponOrder(String couponId, String orderId, final ResponseListener<Result> listener) {
        apiService.createCouponOrder(getCommonParams("User", "CreateCouponOrders"), "App", couponId, orderId).map(new Func1<String, Result>() {
            @Override
            public Result call(String s) {
                return GsonUtils.getObj(s, Result.class);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Result>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(Result s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void upOrderStatus(String orderId, int status, final ResponseListener<Result> listener) {
        apiService.upOrderStatus(getCommonParams("Order", "UpdateTaxiOrderStatus"), orderId, status)

                .map(new Func1<String, Result>() {
                    @Override
                    public Result call(String s) {
                        LogUtil.log("order", "修改订单状态结果：" + s);
                        return GsonUtils.getObj(s, Result.class);
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Result>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                if (listener != null) listener.onResponse(null);
                ExceptionHand.handException(e);
            }

            @Override
            public void onNext(Result s) {
                if (listener != null) listener.onResponse(s);
            }
        });
    }

    public static void getAlPayInfo(String paySerNo, String subject, String body, String price, String type,
                                    final ResponseListener<String> listener) {
        apiService.getAlPayInfo(getCommonParams("AliRSAOderInfo", "GetAliRSAOderInfo"), paySerNo, subject, body, price, type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (listener != null) listener.onResponse(null);
                        ExceptionHand.handException(e);
                    }

                    @Override
                    public void onNext(String s) {
                        if (listener != null)
                            listener.onResponse(s);
                    }
                });
    }


    public static void getWxPreID(String paySerNo, String price, String type,
                                  final ResponseListener<String> listener) {
        apiService.getWxPreID(getCommonParams("AliRSAOderInfo", "GetWeiRSAOderInfo"), paySerNo, price, type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (listener != null) listener.onResponse(null);
                        ExceptionHand.handException(e);
                    }

                    @Override
                    public void onNext(String s) {
                        if (listener != null)
                            listener.onResponse(s);
                    }
                });
    }

    public static void payN(String userId, String type, String payMode, String money, String orderID,
                            String CouponsID, String CouponsAmt,
                            final ResponseListener<String> listener) {
        apiService.payN(getCommonParams("Pocket", "PayOrder_New"), "android", userId, type, payMode, money,
                orderID, CouponsID, CouponsAmt)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (listener != null) listener.onResponse(null);
                        ExceptionHand.handException(e);
                    }

                    @Override
                    public void onNext(String s) {
                        LogUtil.log("pay", "发起支付的结果：" + s);
                        if (listener != null)
                            listener.onResponse(s);
                    }
                });
    }

    public interface ResponseListener<T> {
        void onResponse(T t);
    }

    public static Map<String, String> getCommonParams(String module, String action) {
        Map<String, String> commonParams = new HashMap<>();
        commonParams.put("__from", "android");
        commonParams.put("__ct", UNICODE);
        commonParams.put("module", module);
        commonParams.put("action", action);

        return commonParams;
    }

    public static Retrofit creatClient() {
        return new Retrofit.Builder()
                .baseUrl(SERVER_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(new OkHttpClient.Builder()
                        .connectTimeout(10, TimeUnit.SECONDS)
                        .writeTimeout(30, TimeUnit.SECONDS)
                        .readTimeout(30, TimeUnit.SECONDS)
                        .build())
                .build();
    }
}
